#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <libgen.h>
#include <stdint.h> 
#include <sys/stat.h> 

int main(int argc, char* argv[])
{
    if (argc != 3) 
    {
        perror("argc err");
        return -1;
    }
    char *file1 = argv[1];
    char *file2 = argv[2];
    int my_client = socket(AF_INET, SOCK_DGRAM, 0);
    if(my_client < -1) 
    {
        perror("client err");
        return -1;
    }
    printf("socket OK!\n");
    struct sockaddr_in addr = 
    {
        .sin_family = AF_INET,
        .sin_port = htons(8888),
        .sin_addr.s_addr = INADDR_ANY
    };

    char send_buf[32] = "This is client!";
    char recv_buf[32] = {0};
    if(sendto(my_client, send_buf, sizeof(send_buf), 0, (struct sockaddr*)&addr, sizeof(addr)) < 0)
    {
        perror("sendto err");
        close(my_client);
        return -1;
    }
    printf("send to server:%s\n", send_buf);
    if(recvfrom(my_client, recv_buf, sizeof(recv_buf), 0, NULL, NULL) > 0)
    {
	    printf("recv from server:%s\n", recv_buf);
    }

    char *files[2] = {file1, file2};
    for(int i = 0; i < 2; i++){
	char *filepath = files[i];
	FILE *file = fopen(filepath, "rb");
    if(!file)
        {
	    perror("fopen error");
	    close(my_client);
      	    return -1;
   	}
   	 // 获取文件大小
        struct stat st;
        stat(filepath, &st);
        uint64_t file_size = st.st_size;
        printf("\nFile size: %lu bytes\n", file_size);
        
        char filename[100];
        strncpy(filename, basename(filepath), sizeof(filename)-1);
        filename[sizeof(filename)-1] = '\0';

	printf("%s send.....\n", filename);
	sendto(my_client, filename, sizeof(filename), 0, (struct sockaddr*)&addr, sizeof(addr));
	
	 // 发送文件大小（转换为网络字节序）
        uint64_t net_file_size = htobe64(file_size);
        sendto(my_client, &net_file_size, sizeof(net_file_size), 0, (struct sockaddr*)&addr, sizeof(addr));
	
	char sendbuff[1024];
	size_t readlen;
	
 	while((readlen = fread(sendbuff,1 ,sizeof(sendbuff), file)) > 0){
	    sendto(my_client, sendbuff, readlen, 0, (struct sockaddr*)&addr, sizeof(addr));
	}
	fclose(file);
	printf("%s send success!\n", filename);
	
    }
    close(my_client);
    return 0;
}
